package com.zc.test;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: Selenium
 * @description: HttpClientDemo
 * @author: zengchen
 * @create: 2021-07-15 09:57
 **/
public class HttpClientDemo {

    public static void main(String[] args) {
        String loginUrl = "https://login.taobao.com/newlogin/login.do?appName=taobao&fromSite=0&_bx-v=2.0.31";
        String queryReginUrl = "http://domani/xxx/system/getRegionList.do";
        //第一次登录会保存cookie
        doPost(loginUrl, getLoginNameValuePairList());
        //第二次操作会调用已经存在的cookie
//        doPost(queryReginUrl, getQueryNameValuePairList());
    }

    static CookieStore cookieStore = null;

    /**
     * 组装登录参数
     * @return
     */
    public static List<NameValuePair> getLoginNameValuePairList() {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("(Content)","loginId=zc20120902&password2=d2f3f367671d57cfacddf0224183c10852e25ac2ac0d965fa4654cb658d1e13ebf7e4808e9c251dd23b826e5c7a271e5bee453b1d8a2edb6e20737bbf583a93b8bf0172077bfd037a84f46c9315f3fb03bfbb76417547ca48e2e4ff8c7733d89af2f9717dcb889307e7feb962792e2227d00784cd6df0c639b10e6af212c8bef&keepLogin=false&ua=140%23kkFoU7YizzPrhzo22xqTC3SogjHsgSHj84pzCSMImZLgK%2FLavf0xY3a4QR9ywaZO9ZwjNhUVhHe3nNVe0lr%2F76hqzzngyvwv9auzzjPWIHoBUbeyU6W1VYmRtCFi22U3l61zzPHtG8rg4sCi2Pc3VCAezFziHEGtldrozkX7VMmtlY1o2bN4VPf0zaXV2v5YlRTDePrIjw7tuQ%2BDaIK4u5ZpJjBP2IwNfwAFj7XCdAD3e1CXa2N5%2FVqUVvMnKYyy%2Bqi%2FwGqTRopA5dtovu5kUo%2B%2FT0cK4Uu5qAc4MyAxB5lRr2A1nAFrmqfvaW6h%2FaFlL9yjs2jCdlAomNNefszMsc8J6bLbBTseQD6EgI9UbWjfPx1qBSC3OrBIeH54DLZ8Czjfz9pOFEyzY%2B3WFvS0DtNTseUWKR0WFhh9Pd9vaKYa7CTL4NamfgZPzBHzvrSWjZlTsj%2BkR3rRZMf1%2B3sHgIHE76bS5JRM51WamwqN1dYAx3w23pFV4hAR5giaCmZIn2QybTo1mEZ%2BhH0kNHxkkgJg%2FTdlaYUBLZMxby%2FPXzVxA9TjidprkZlTs%2FkVcbcUz3bb7pPJ1D1KnlZ5BW8qlj2WdM1bYplRoz4GBsES4AAhQla9O7eyYympkN26k07FUfx36lWCzRQQgNOnzre7LkvglilgGVUMItGHje%2FY9KFVULNJyeTPN0DP2R0XuGJ0aOb%2FsVxPALLAECTwq%2FBg5Rtyts0UK%2BsFds3uaYKBidjp9HQ%2BXRSmzAXyb3%2FVKLpVh15C2knlZ6QEj%2Fj4nXs4q1W%2F%2BnHWlLOOnHeakLPk4DITWr7Pfn6xHnVDjEQqxxvw9VVHV0mCJj4Nl6GJucTRdxXY%2B74M72Hrrurb5R%2Frwhq7%2FQbuY3zPcJm6%2BnteB5c0DQFQxrlaFNiOxnF%3D&umidGetStatusVal=255&screenPixel=1536x864&navlanguage=zh-CN&navUserAgent=Mozilla%2F5.0%20%28Windows%20NT%2010.0%3B%20WOW64%3B%20Trident%2F7.0%3B%20.NET4.0C%3B%20.NET4.0E%3B%20.NET%20CLR%202.0.50727%3B%20.NET%20CLR%203.0.30729%3B%20.NET%20CLR%203.5.30729%3B%20rv%3A11.0%29%20like%20Gecko&navPlatform=Win32&appName=taobao&appEntrance=taobao_pc&_csrf_token=mM6sAf46OzgSsYjfU1N8y8&umidToken=4c25c771e0a03f8afacf23fb595bbf420ad6382f&hsiz=1babadc788a71178adb29bd3976e8852&bizParams=&style=default&appkey=00000000&from=tbTop&isMobile=false&lang=zh_CN&returnUrl=https%3A%2F%2Fwww.taobao.com%2F&fromSite=0&bx-ua=212!h1aWZg/hWWmntamvUWh5EYVITO4waWWPE9hZvAsBWpl6T9z3MBWHS5iILA4hEPlJZ7VvyCPE95yyx96wvaWpwYlmHQ6av3IJZZJXghR5pmMgT+P9zolCGSI8yoNHgOpm9p8wkR/Oi4tHwOI8HjrZBjQIOPbXK0U0z7cLZga3gtmi9kTGEn25scETawjpXJpQ7FpouWnx8O0dARcnVx+DmiQJMAEYuon+00A24TqIClmL/hY1YgS/fCsICWJ4JfrKKVafE66qrkBEfoHxq84rllZoQJITzZiAvfnlVCvnT9rJbccMJZhyQidEyH28/3WOw9t65TzVwEB+uvRDH37DiGtShyQnsLHRuXpDKS/e+uXjJAI1arPYxALArPMznDzsIubQmhtPakzMdby2GntSaYXshjHyMzn2+09D1FeC7o0nxGoPf2CCuncD3UPYsrfiSgqVTUn1IOioqWZVckxFkdM26oSeIiMeBTsKbWG7cUKRKG7HrtHXQLoS5Wh5J6rk05mPKFyJijL3iV9ZAE+djj+dZmpnWU7jMQJUH5La9r0Uhf4VBSHHVF4Av8+P3njvhmpO4Q6cm8poXDNxBb/ptW6HBlqaa7Dbe7iLNObyY5VNP8KYIAuVUnjVpoGN+KkSCL/+uLFtB/V4ZeIi+qaObVihYdw9M87fU5INAhWBXlXSqq4vRPCjwOlDiZc1SquTcpzW3NKB4z16lFB5IGSGvfQ13+3OeoA071xnHF50iHk73d9tTxrTfNQJr9sRj0Uei4QxoHMqmfPAoioyKywBXyxb8DtS//7gz4fwG3Ed89TLmMTJcxz8hunNGD2vKvHBrkkO7kfxLQCyv+2Qa4kwuZ5z06O3PPP+YMhKHsiYshYc4ohIrKnoSxHWaghxPnZ7YeQEYgT/LHYRPN8GP69zcLHwMr92oXe+0KbHkP2mMmTEJrxzoYQtL0617A5+wobSl5rX2y/nLEo1LJL0GJgl+8zzqL9+UYNbFQthKD1lqB77w3DCWwuHCIZSQ0zTgJcYyxT4pq9jjUQdTaFFcuIdP8lKOidrh0Q5O6fsGD16gIfhthrlFNgJDZuQfYcekpvviUC31bPOt7a13zJXxc+46tTGODITO381+0tSQ/hxK3odP/NugsqxqEAh3O/geiJGthUxrwTHXFoGqWXnBDLKiAL0zLfRWkQIbs4CZORtWW413uzpVEiQN0Qo1wl8vNavdvttQAWDunJuJk2rLoESasf9cRZFE4bnUGtDuPO+H1X8fegvdI9tfYqCFRUwSjwmsP8QeuGNQe6d7puGaTQ1fN3ioTBt1r+durCEEQaBDh0EmPqTcmvxPnkXgcv+32+uIQ04FzaEnZI0p7ld4wmC4s6eQRwRG/0AxRs+5eJGjY3FX87sa0GfDSIaP/LMY9JiwUfwXBBt/HucuDZtnV4bRDWXONdADRn9LSC02N95Fj8oqvqC3u/CaNa2aLUFAV0bX8GJhQxuXrUaHKnQ0ra8xf8XCrYkAduEma8IQwaOZ8GJy3jXGV1VVuqdzUBny62QHDrXAHBEFdqxQx4vxEdFtmwe4YGOe5cK/tdqwXSatxpP4y9fOe132SuxXF3OtzCnCYcSbecW7tT48kEnrYe69Gm1YRBXPB3yPvSKLC5DdmONoi/HYlE4eiLZ5f+a&bx-umidtoken=T2gAhCEgphKY_oF0dM7EvU5i9JYkmtvRtbVrDfOfTDYb5FfgWPhgSNxrRlkbNGI_Afk="));
        return params;
    }
    /**
     * 组装操作参数
     * @return
     */
    public static List<NameValuePair> getQueryNameValuePairList() {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("regionNo", "xxx"));
        params.add(new BasicNameValuePair("pageNo", "xxx"));
        params.add(new BasicNameValuePair("pageSize", "xxx"));
        return params;
    }
    /**
     * 将cookie保存到静态变量中供后续调用
     * @param httpResponse
     */
    public static void setCookieStore(HttpResponse httpResponse) {
        System.out.println("----setCookieStore");
        cookieStore = new BasicCookieStore();
        // JSESSIONID
        Header[] headers = httpResponse.getHeaders("Set-Cookie");
        System.out.println(headers.length);
//        String JSESSIONID = setCookie.substring("JSESSIONID=".length(),
//                setCookie.indexOf(";"));
//        System.out.println("JSESSIONID:" + JSESSIONID);
//        // 新建一个Cookie
//        BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",JSESSIONID);
//        cookie.setVersion(0);
//        cookie.setDomain("domain");
//        cookie.setPath("/xxx");
//        cookieStore.addCookie(cookie);
    }

    public static String doPost(String postUrl,List<NameValuePair> parameterList) {
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = null;
        if(cookieStore!=null){
            closeableHttpClient = httpClientBuilder.setDefaultCookieStore(cookieStore).build();
        }else{
            closeableHttpClient = httpClientBuilder.build();
        }
        HttpPost httpPost = new HttpPost(postUrl);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000).setConnectTimeout(30000).build();
        httpPost.setConfig(requestConfig);
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameterList, "UTF-8");
            httpPost.setEntity(entity);
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            setCookieStore(response);

            HttpEntity httpEntity = response.getEntity();
            retStr = EntityUtils.toString(httpEntity, "UTF-8");
            System.out.println(retStr);
            // 释放资源
            closeableHttpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retStr;
    }
}
